package com.lagou.edu.minicat.core;

import com.lagou.edu.minicat.Servlet;
import com.lagou.edu.minicat.base.LifecycleBase;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class Context extends LifecycleBase {
    private Map<String, Wrapper> wrapperMap = new HashMap<>();

    private String contextName;

    private ClassLoader classLoader;

    public void addWrapper(Wrapper wrapper) {
        wrapperMap.put(wrapper.getUrlPattern(), wrapper);
    }

    @Override
    protected void initInternal() {
        for (Map.Entry<String, Wrapper> entry : wrapperMap.entrySet()) {
            Wrapper wrapper = entry.getValue();
            try {
                Class<?> clazz = this.classLoader.loadClass(wrapper.getClassName());
                Servlet servlet = (Servlet) clazz.newInstance();
                wrapper.setServlet(servlet);
                servlet.init();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void startInternal() {
    }

    /**
     * 通过urlPatten获取wrapper
     *
     * @param urlPattern
     * @return
     */
    public Wrapper findWrapper(String urlPattern) {
        return wrapperMap.get(urlPattern);
    }
}
